package com.my.code;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.my.entity.TysbdmDO;
import com.my.utils.HttpUtil;
import com.my.utils.JsonUtil;
import com.my.utils.Md5Util;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author mayong
 * @since 2024/7/23
 */
@Slf4j
@Service
public class CodingService {

    private String user = "ysga_spa";

    private String password = "LEb3mEXhmDehz%EtT6nJ";

    private String appkey = "1260908914061344768";

    //02 编码赋码_数公基对象编码及注册接口(支持返回数公基码、北斗码)_新
    private static final String REGISTER = "http://59.208.24.2/gateway/api/1/get/register";

    //01
    private static final String SIGN_IN_URL = "http://59.208.24.2/gateway/api/1/get/bmfmjqtoken?user=%s&time=%s&secret=%s";

    //03
    private static final String CANCEL = "http://59.208.24.2/gateway/api/1/cancellation?code=%s&token=%s";

    //04
    private static final String ENABLE = "http://59.208.24.2/gateway/api/1/antiCancelByCode?code=%s&token=%s";


    @Resource(name = "restTemplateIgnoreSSL")
    private RestTemplate restTemplateIgnoreSSL;


    private String token = null;


    //03 注销
    public void cancel(String code) {
        if (token == null) {
            signIn();
        }
        String url = String.format(CANCEL, code, token);
        log.info("03 注销对象的url: " + url);
        HttpHeaders headers = new HttpHeaders();
        headers.add("AppKey", appkey);
        String res = HttpUtil.get(restTemplateIgnoreSSL, url, headers, String.class);
        log.info("03 注销对象的响应: " + res);
        getInner2(res);
    }

    // 04 重启
    public void enable(String code) {
        if (token == null) {
            signIn();
        }
        String url = String.format(ENABLE, code, token);
        log.info("04 重启对象的url: {}", url);
        HttpHeaders headers = new HttpHeaders();
        headers.add("AppKey", appkey);
        String res = HttpUtil.put(restTemplateIgnoreSSL, url, headers, String.class);
        log.info("04 重启对象的响应: {}", res);
        getInner2(res);
    }

    private void getInner2(String res){
        OuterResponse outer = JsonUtil.object(res, OuterResponse.class);
        if (outer.code != 200) {
            throw new RuntimeException(outer.getMsg());
        }
        InnerResponse inner = outer.getData();
        if (inner.code != 0 && inner.code != 202) {
            throw new RuntimeException(inner.msg);
        }
        log.info(inner.msg);
    }

    //02 赋码
    public CodeData register(TysbdmDO obj) {
        if (token == null) {
            signIn();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("AppKey", appkey);
        headers.add("token", token);
        MultiValueMap<String, String> map = obj.buildParams();
        log.info("02 编码请求参数： " + JsonUtil.json(map));
        String res = HttpUtil.postByFormUrlencoded(restTemplateIgnoreSSL, REGISTER, map, headers, String.class);
        log.info("02 编码响应参数： " + res);
        // {"code":"200","msg":"请求成功","data":"{\"code\":0,\"msg\":\"请求成功。\",\"success\":true,\"data\":{\"isOld\":true,\"beidou_3d\":null,\"beidou_2d\":\"N50H352A49216520\",\"code\":\"421124405002000000001\",\"entity_id\":\"01e9d3b2-4579-11ef-83c0-fa163ecc2f25\"}}","total":0}
        CodeData codeData;
        try {
            InnerResponse inner = getInner(res);
            codeData = JsonUtil.convertValue(inner.data, CodeData.class);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage() + "; 原始响应: " + res);
        }
        return codeData;
    }


    // 01 token
    private void signIn() {
        String time = String.valueOf(System.currentTimeMillis());
        String secret = Md5Util.sign(time + password);
        String url = String.format(SIGN_IN_URL, user, time, secret);
        log.info("01 获取token的请求url: " + url);
        HttpHeaders headers = new HttpHeaders();
        headers.add("AppKey", appkey);
        String res = HttpUtil.get(restTemplateIgnoreSSL, url, headers, String.class);

        log.info("01 请求结果token的原始响应 : " + res);
        // res = {"code":"200","msg":"请求成功","data":"{\"code\":0,\"msg\":\"请求成功。\",\"success\":true,\"data\":\"b338341cd12f479aa1eb0a5db2a5a695\"}","total":0}
        InnerResponse inner = getInner(res);
        token = (String) inner.data;
    }


    private InnerResponse getInner(String res) {
        OuterResponse outer = JsonUtil.object(res, OuterResponse.class);
        if (outer.code != 200) {
            throw new RuntimeException(outer.getMsg());
        }
        InnerResponse inner = outer.getData();
        if (inner.code != 0) {
            throw new RuntimeException(inner.msg);
        }
        return outer.getData();
    }


    @Data
    public static class OuterResponse {
        private int code;
        private String msg;
        private String data;
        private int total;

        public InnerResponse getData() {
            return JsonUtil.object(data, InnerResponse.class);
        }
    }

    @Data
    public static class InnerResponse {
        private int code;
        private String msg;
        private boolean success;
        private Object data;
    }

    @Data
    public static class CodeData {

        @JsonProperty(value = "isOld")
        private boolean old;

        @JsonProperty(value = "beidou_3d")
        private String beiDou3d;

        @JsonProperty(value = "beidou_2d")
        private String beiDou2d;

        @JsonProperty(value = "code")
        private String code;

        @JsonProperty(value = "entity_id")
        private String entityId;
    }


}
